#include "udpsendfilewidget.h"
#include "ui_udpsendfilewidget.h"

#include <QFileDialog>
#include <QFileInfo>
#include <QFile>
#include <QDebug>
#include <QMessageBox>
#include <QTextStream>

UdpSendFileWidget::UdpSendFileWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UdpSendFileWidget)
{
    ui->setupUi(this);

    udpSocket = new QUdpSocket(this);
    timer = new QTimer(this);
    isSended = false;
    //path = QFileDialog::getOpenFileName(this);

    connect(timer, SIGNAL(timeout()), this, SLOT(slotTimeout()));
    connect(udpSocket, SIGNAL(readyRead()), this, SLOT(readBack()));
}

UdpSendFileWidget::~UdpSendFileWidget()
{
    delete ui;
}

void UdpSendFileWidget::on_pushButtonBrowse_clicked()
{
    path = QFileDialog::getOpenFileName(this);
    ui->lineEditPath->setText(path);
}

void UdpSendFileWidget::slotTimeout()
{
    quint16 port = 9998;
    //QByteArray send_buf(512);
    QString send_buf;

    file = new QFile(path);
    bool ok = file->open(QIODevice::ReadOnly);
    if(!ok)
    {
       QMessageBox::warning(this,NULL,file->errorString());
       return;
    }
    else
    {
//        qint64 lineLength = file->readLine(send_buf, sizeof(send_buf));
//        if(lineLength != -1)
//        {
//            int length = udpSocket->writeDatagram(send_buf, lineLength,
//                                                  QHostAddress::Broadcast, port);
//            if(length != lineLength)
//            {
//                qDebug("Send file fail !");
//            }
//        }
        QDataStream in(file);
        in >> send_buf;
        int length = udpSocket->writeDatagram(send_buf.toLatin1(), send_buf.toLatin1().length(),
                                              QHostAddress::LocalHost, port);
        if(length != send_buf.toLatin1().length())
        {
            qDebug("Send file fail !");
        }

        file->close();
    }
}

void UdpSendFileWidget::readBack()
{
    while(udpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        QHostAddress host;
        quint16 port;
        datagram.resize(udpSocket->pendingDatagramSize());
        udpSocket->readDatagram(datagram.data(), datagram.size(), &host, &port);
        qDebug() << host.toString() + "[" + QString::number(port) + "] : " + QString(datagram);
    }
}

void UdpSendFileWidget::on_pushButtonSend_clicked()
{
    if(!isSended)
    {
        timer->start(1000);
        isSended = true;
        ui->pushButtonSend->setText("Stop");
    }
    else
    {
        timer->stop();
        isSended = false;
        ui->pushButtonSend->setText("Send");
    }
}
